from sqlalchemy import table
from sqlalchemy.ext.declarative import declarative_base, AbstractConcreteBase

from environment import environment, engine

Base = declarative_base(engine)

# 解决错误does not have a __table__ or __tablename__ specified and does not inherit from an existing table-mapped class.
# 添加 AbstractConcreteBase 继承或者在类中添加__abstract__ = True 表明当前类只用于继承


class BaseModel(AbstractConcreteBase, Base):

    @classmethod
    def db(self):
        return environment.db

    # 批量增加
    @classmethod
    def batch_add(cls, info_list):
        table_props = [
            _i.name for _i in cls.__table__.columns if _i.name != "id"]
        # 过滤表格没有的属性
        info_list = [cls.parse_table_prop(
            insert_obj, table_props) for insert_obj in info_list]
        cls_list = [cls(**_i) for _i in info_list]
        cls.db().add_all(cls_list)
        cls.db().commit()

    # 批量删除
    # 批量修改

    @staticmethod
    def parse_table_prop(obj, table_props):
        for _key in obj.keys():
            if _key in table_props:
                return obj
